/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.thirdapi.weixin;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;

/**
 * 
 * @author max.zheng
 * @create 2015-6-27上午11:26:12
 * @since 1.0
 * @see
 */
public class WeiXinPayUtil {

	// appid
	// 请同时修改 androidmanifest.xml里面，.PayActivityd里的属性<data
	// android:scheme="wxb4ba3c02aa476ea1"/>为新设置的appid "wx4461e99ba5b808ab";// "1250725301";//
	public static final String APP_ID = "wx4461e99ba5b808ab";//"wxf2f565574a968187";

	// 商户号
	public static final String MCH_ID = "1250725301";//"1233848001";

	// API密钥，在商户平台设置
	public static final String API_KEY = "15980934120youparking15980934120";
	
	
	public static final String NOTIFY_URL = "http://121.41.88.185:8080/parkWeiXinNotify.action";

	/**
	 * 
	 * @author max.zheng
	 * @create 2015-6-27上午11:26:13
	 * @modified by
	 * @param args
	 */
	public static void main(String[] args) {
//		Map<String, String> xml = createWeiXinPreOrder("1","http://121.40.35.3/test","");
//		System.out.println(xml);
	}



	/**
	 * 
	 * @author max.zheng
	 * @create 2015-6-28下午8:32:43
	 * @modified by
	 * @return
	 */
	public static Map<String, String> createWeiXinPreOrder(String totalFee,String outTradeNo) {
		String url = String
				.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
		String entity = genProductArgs(totalFee,outTradeNo);
		
		byte[] buf = Util.httpPost(url, entity);

		String content = new String(buf);
		Map<String,String> xml=decodeXml(content);
		return xml;
	}
	
	
	
	public static Map<String,String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = new MXParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
					case XmlPullParser.START_DOCUMENT:

						break;
					case XmlPullParser.START_TAG:

						if("xml".equals(nodeName)==false){
							//实例化student对象
							xml.put(nodeName,parser.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return null;

	}

	private static String genProductArgs(String totalFee,String outTradeNo) {
		StringBuffer xml = new StringBuffer();

		try {
			String nonceStr = genNonceStr();

			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams
					.add(new BasicNameValuePair("appid", APP_ID));
			packageParams.add(new BasicNameValuePair("body", "weixin"));
			packageParams
					.add(new BasicNameValuePair("mch_id", MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url",
					NOTIFY_URL));
			packageParams.add(new BasicNameValuePair("out_trade_no",
					outTradeNo));
			packageParams.add(new BasicNameValuePair("spbill_create_ip",
					"127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", totalFee));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));

			String xmlstring = toXml(packageParams);

			return xmlstring;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	private static String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");


			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");
		return sb.toString();
	}
	/**
	 生成签名
	 */

	private static String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(API_KEY);
		
		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return packageSign;
	}
	private static String genOutTradNo() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	private static String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
				.getBytes());
	}
	
	public static String genPaySign(Map<String, String> prepayMap) {

//		req.appId = Constants.APP_ID;
//		req.partnerId = Constants.MCH_ID;
//		req.prepayId = resultunifiedorder.get("prepay_id");
//		req.packageValue = "Sign=WXPay";
//		req.nonceStr = genNonceStr();
//		req.timeStamp = String.valueOf(genTimeStamp());


		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", APP_ID));
		signParams.add(new BasicNameValuePair("noncestr", NOTIFY_URL));
		signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
		signParams.add(new BasicNameValuePair("partnerid", MCH_ID));
		signParams.add(new BasicNameValuePair("prepayid", prepayMap.get("prepay_id")));
		signParams.add(new BasicNameValuePair("timestamp", System.currentTimeMillis() / 1000+""));

//		req.sign = genAppSign(signParams);

//		sb.append("sign\n"+req.sign+"\n\n");
		return genAppSign(signParams);
	}
	
	public static String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(API_KEY);
		
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return appSign;
	}

}
